package com.ygqh.baby.controller.admin;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.handler.ReturnPriceHandler;
import com.ygqh.baby.model.OrderDetail4ReturnOff;
import com.ygqh.baby.model.OrderInfo4ReturnOff;
import com.ygqh.baby.model.YgReturnInfoModel;
import com.ygqh.baby.model.YgReturnOrderInfoModel;
import com.ygqh.baby.po.AdminUser;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgReturnOrder;
import com.ygqh.baby.po.YgReturnOrderOffLine;
import com.ygqh.baby.service.*;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/admin/returnorderoff")
public class ReturnOrderOffController extends BaseController<Object, java.lang.Long> {

    @Autowired
    private YgReturnOrderService ygReturnOrderService;
    @Autowired
    private YgReturnOrderLogService ygReturnOrderLogService;
    @Autowired
    private FileService fileService;
    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private YgReturnOrderOffLineService ygReturnOrderOffLineService;
    @Autowired
    private ReturnPriceHandler returnPriceHandler;

    @RequestMapping("seachReturnOrder")
    @ResponseBody
    public Map<String, Object> seachReturnOrder(Long orderId, QueryInfo queryInfo, Date startDate, Date endDate, String expressCode) {
        ResultSet<YgReturnOrderOffLine> resultSet = ygReturnOrderOffLineService.search(queryInfo, orderId, startDate, endDate, expressCode, null);
        return resultSet.toDatatables(null);
    }

    @RequestMapping("getOrderInfo")
    @ResponseBody
    public Map<String, Object> getOrderInfo(Long orderId) {

        OrderInfo4ReturnOff orderInfo = ygReturnOrderOffLineService.findOrderInfoToOffReturn(orderId);

        BigDecimal refundPrice = new BigDecimal("0.00");
        BigDecimal refundAccountPrice = new BigDecimal("0.00");
        for (OrderDetail4ReturnOff detail : orderInfo.getDetailList()) {
            refundPrice = refundPrice.add(detail.getRefundPrice());
            refundAccountPrice = refundAccountPrice.add(detail.getRefundAccountPrice());

        }
        orderInfo.setRefundPrice(refundPrice);
        orderInfo.setRefundAccountPrice(refundAccountPrice);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderInfo", orderInfo);
        return map;
    }

    /**
     * 获取退货金额
     *
     */
    @Deprecated
    @RequestMapping(value = "getReturnPriceOld", method = RequestMethod.GET)
    @ResponseBody
    public Message getReturnPrices(String returnInfo, String callback) {
        YgReturnInfoModel infoModel = JsonUtils.toObject(returnInfo, YgReturnInfoModel.class);
        Message msg = ygReturnOrderService.getReturnPrice(infoModel);
        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
        if (msg.getType().equals(Message.Type.error)) {
            return msg;
        }
        YgOrder order = ygOrderService.findByOrderId(infoModel.getOrderId());
        YgReturnInfoModel info = (YgReturnInfoModel) msg.getExtra();

        BigDecimal residualRefundPrice = ygReturnOrderService.residualRefundPrice(order.getOrderId());
        BigDecimal subtract = residualRefundPrice.subtract(info.getReturnPrice());
        if (subtract.abs().compareTo(new BigDecimal("1.00")) <= 0) {
            info.setReturnPrice(residualRefundPrice);
        }
        BigDecimal refundAccountPrice = new BigDecimal(0);
        // 退款多于实际付款，优先退实际支付的
        BigDecimal lastPaidPrice = residualRefundPrice.subtract(order.getAccountPrice());
        if (info.getReturnPrice().compareTo(lastPaidPrice) > 0) {
            refundAccountPrice = info.getReturnPrice().subtract(lastPaidPrice);
        }
        BigDecimal refundPrice = info.getReturnPrice().subtract(refundAccountPrice);
        map.put("expressPrice", info.getExpressPrice());
        map.put("totalRefund", info.getReturnPrice());
        map.put("refundPrice", refundPrice);
        map.put("refundAccountPrice", refundAccountPrice);
        return Message.success(map);

    }

    /**
     * 获取退款金额
     *
     * @param returnInfo 退货信息
     * @return Message
     */
    @RequestMapping(value = "getReturnPrice", method = RequestMethod.GET)
    @ResponseBody
    public Message getReturnPricesV2(String returnInfo) {
        YgReturnInfoModel infoModel = JsonUtils.toObject(returnInfo, YgReturnInfoModel.class);
        return returnPriceHandler.getReturnPrice(infoModel);

    }


    /**
     * 保存退货单
     *
     */
    @RequestMapping(value = "saveReturnOrderOff", method = RequestMethod.GET)
    @ResponseBody
    public Message saveReturnOrder(String returnInfo, String returnReason, Long userId, String imgPaths, String expressCompany, String expressCode) {
        if (StringUtil.isEmpty(returnReason)) {
            return Message.error("请填写问题说明。", null);
        }

        AdminUser adminUser = SessionUtil.getCurrentUser();
        YgReturnInfoModel infoModel = JsonUtils.toObject(returnInfo, YgReturnInfoModel.class);
        Message msg = returnPriceHandler.getReturnPrice(infoModel);
        if (msg.getType().equals(Message.Type.error)) {
            return msg;
        }
        YgReturnInfoModel info = (YgReturnInfoModel) msg.getExtra();
        Message message = ygReturnOrderOffLineService.saveReturnOrder(infoModel, returnReason, imgPaths, info, userId, adminUser.getTrueName());

        if (StringUtil.isNotBlank(expressCode) && message.getType().equals(Message.Type.success)) {
            this.userSendOrder((Long) message.getExtra(), expressCompany, expressCode);
        }
        return message;
    }

    @RequestMapping(value = "saveReturnOrderOffV2", method = RequestMethod.GET)
    @ResponseBody
    public Message saveReturnOrderOffV2(String returnInfo, ReturnReasonType returnReasonType, String returnReason,
                                        Long userId, String imgPaths, String expressCompany, String expressCode) {
        if (returnReasonType == null) {
            return Message.error("请选择退换货原因。", null);
        }
        AdminUser adminUser = SessionUtil.getCurrentUser();
        YgReturnInfoModel infoModel = JsonUtils.toObject(returnInfo, YgReturnInfoModel.class);

        Boolean exitNotCompleteReturn = ygReturnOrderService.isExitNotCompleteReturn(infoModel.getOrderId(),
                ReturnType.Return, null);
        if (exitNotCompleteReturn) {
            return Message.error("存在未完成退货单", exitNotCompleteReturn);
        }
        Message msg = returnPriceHandler.getReturnPrice(infoModel);
        if (msg.getType().equals(Message.Type.error)) {
            return msg;
        }
        YgReturnInfoModel info = (YgReturnInfoModel) msg.getExtra();
        Message message = ygReturnOrderOffLineService.saveReturnOrderV2(info, returnReasonType, returnReason,
                imgPaths, userId, adminUser.getTrueName());
        if (StringUtil.isNotBlank(expressCode) && message.getType().equals(Message.Type.success)) {
            this.userSendOrderV2((Long) message.getExtra(), expressCompany, expressCode);
        }
        return message;
    }

    @RequestMapping("returnorderDetail")
    @ResponseBody
    public YgReturnOrderInfoModel returnorderDetail(String returnCode, Long userId) {

        return ygReturnOrderOffLineService.findReturnOrderInfo(returnCode, userId);
    }

    @RequestMapping("userSendOrderV2")
    @ResponseBody
    public Message userSendOrderV2(Long id, String userExpressCompany, String userExpressCode) {
        YgReturnOrder offLine = ygReturnOrderService.findById(id);
        YgOrder order = ygOrderService.findByOrderId(offLine.getOrderId());
        offLine.setUserExpressCode(userExpressCode);
        offLine.setUserExpressCompany(userExpressCompany);
        offLine.setUpdateBy(getSession().getTrueName());
        offLine.setUpdateTime(new Date());
        offLine.setReceiver(order.getReceiver());
        offLine.setProvinceName(order.getProvinceName());
        offLine.setCityName(order.getCityName());
        offLine.setAreaName(order.getAreaName());
        offLine.setAddress(order.getAddress());
        offLine.setTelPhone(order.getTelPhone());
        ygReturnOrderService.update(offLine);
        ygReturnOrderLogService.addReturnOrderLog(offLine.getReturnCode(), "您的退货已寄回。物流信息：" + userExpressCompany + userExpressCode, ReturnStatus.WaitingInStock,
                getSession().getTrueName(), null);
        return SUCCESS_MESSAGE;

    }

    @RequestMapping("userSendOrder")
    @ResponseBody
    public Message userSendOrder(Long id, String userExpressCompany, String userExpressCode) {
        YgReturnOrderOffLine offLine = ygReturnOrderOffLineService.findById(id);
        YgOrder order = ygOrderService.findByOrderId(offLine.getOrderId());
        offLine.setUserExpressCode(userExpressCode);
        offLine.setUserExpressCompany(userExpressCompany);
        offLine.setUpdateBy(getSession().getTrueName());
        offLine.setUpdateTime(new Date());
        offLine.setReceiver(order.getReceiver());
        offLine.setProvinceName(order.getProvinceName());
        offLine.setCityName(order.getCityName());
        offLine.setAreaName(order.getAreaName());
        offLine.setAddress(order.getAddress());
        offLine.setTelPhone(order.getTelPhone());
        ygReturnOrderOffLineService.update(offLine);
        ygReturnOrderLogService.addReturnOrderLog(offLine.getReturnCode(), "您的退货已寄回。物流信息：" + userExpressCompany + userExpressCode, ReturnStatus.WaitingInStock,
                getSession().getTrueName(), null);
        return SUCCESS_MESSAGE;

    }

    @RequestMapping("upLoadReturn")
    @ResponseBody
    public Message upLoadReturn(Long id, String returnCode, FileType fileType, @RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest request,
                                HttpServletResponse response) throws IOException {

        String url = fileService.upload2Oss(fileType, uploadFile, returnCode);
        if (url.length() > 0) {
            YgReturnOrderOffLine offLine = new YgReturnOrderOffLine();
            offLine.setId(id);
            offLine.setIsUpload(true);
            ygReturnOrderOffLineService.update(offLine);

        }
        return SUCCESS_MESSAGE;
    }

}
